package com.xing.todolist.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.paging.PagingDataAdapter;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.xing.app.myutils.Utils.DrawableBuilder;
import com.xing.todolist.R;
import com.xing.todolist.databinding.TodoListFragmentItemBinding;
import com.xing.todolist.db.base.TodoMsg;
import com.xing.todolist.listener.OnItemClickListener;

public class TodoListFragmentAdapter extends PagingDataAdapter<TodoMsg, TodoListFragmentAdapter.VH> {

    private OnItemClickListener<TodoMsg> mOnItemClickListener;

    public TodoListFragmentAdapter() {
        super(new DiffUtil.ItemCallback<TodoMsg>() {
            @Override
            public boolean areItemsTheSame(@NonNull TodoMsg oldItem, @NonNull TodoMsg newItem) {
                return false;
            }

            @Override
            public boolean areContentsTheSame(@NonNull TodoMsg oldItem, @NonNull TodoMsg newItem) {
                return false;
            }
        });
    }

    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        TodoListFragmentItemBinding binding = DataBindingUtil.inflate(
                LayoutInflater.from(parent.getContext()),
                R.layout.todo_list_fragment_item,
                parent,
                false);

        binding.getRoot().setBackground(new DrawableBuilder()
                .setColor(parent.getContext().getColor(R.color.green_8))//绿色
                .setRadius(20f).create());

        return new VH(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position) {
        /*
         * 测试中发现 onBindViewHolder 会随着滑动而多次调用
         * 且getItem所获得的对象，会一直存在于栈内，如果我在此方法中对getItem所获取的对象进行修改
         * 那么这种修改在栈内会被持久性保存
         */
        TodoMsg bean = getItem(position);

        holder.bind(bean, v -> {
            // 准备监听事件
            if (getOnItemClickListener() != null) {
                getOnItemClickListener().onItemClick(holder.getBindingAdapterPosition(), holder.mBinding.getData());
            }
        });

    }

    public OnItemClickListener<TodoMsg> getOnItemClickListener() {
        return mOnItemClickListener;
    }

    public void setOnItemClickListener(OnItemClickListener<TodoMsg> onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    public static class VH extends RecyclerView.ViewHolder {

        private TodoListFragmentItemBinding mBinding;

        public VH(TodoListFragmentItemBinding binding) {
            super(binding.getRoot());
            mBinding = binding;
        }

        public void bind(TodoMsg bean, View.OnClickListener listener) {
            mBinding.setData(bean);
            mBinding.setListener(listener);
        }
    }

}
